package edu.school.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import edu.school.entity.User;
import edu.school.entity.UserExample;
import edu.school.mapper.UserMapper;
import edu.school.service.UserService;
import edu.school.utils.ImgUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author kabuda
 * @create 2023-09-30 19:33
 */
@Service("userService")
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean register(User record) {
        return userMapper.insert(record) == 0 ? false : true;
    }

    @Override
    public PageInfo<User> pageList(Integer pageNumber, Integer pageSize, User user) {
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        if (user != null) {
            if (!StringUtils.isEmpty(user.getStuno())) {
                //拼接模糊查询
                criteria.andStunoLike("%" + user.getStuno() + "%");
            }
            if (!StringUtils.isEmpty(user.getNickname())) {
                //拼接模糊查询
                criteria.andNicknameLike("%" + user.getNickname() + "%");
            }
        }
        PageHelper.startPage(pageNumber, pageSize);
        List<User> users = userMapper.selectByExample(example);
        PageInfo<User> info = new PageInfo<>(users);
        return info;
    }

    @Override
    public User findById(Integer id) {
        User user = userMapper.selectByKey(id);
        return user;
    }

    @Override
    public boolean edit(User user) {
        //删除图片
        User user1 = userMapper.selectByKey(user.getId());
        if (user1.getPhoto() != user.getPhoto()) {
            ImgUtils.delete(user1.getPhoto());
        }
        //修改
        int result = userMapper.updateByPrimaryKey(user);
        return result == 1;
    }

    @Override
    public boolean delete(Integer id) {
        User user = userMapper.selectByKey(id);
        ImgUtils.delete(user.getPhoto());
        int i = userMapper.deleteByPrimaryKey(id);
        return i==1;
    }

    @Override
    public boolean deletemany(int[] ids) {
        //删图片
        for (int id : ids) {
            User user = userMapper.selectByKey(id);
            ImgUtils.delete(user.getPhoto());
        }
        //删数据
        int result=userMapper.batchDelete(ids);
        if(result==ids.length){
            return true;
        }else{
            return false;
        }
    }

    @Override
    public User login(User user) {
        User u=userMapper.findUser(user);
        return u;
    }
}

